<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>PDF转图片(多页多张图)</title>
  </head>

  <body>
    <!-- 用于显示图片的容器 -->
    <div id="pdf-container"></div>

    <!-- 引入本地的pdf.js和pdf.worker.js -->
    <script src="./js/pdf.min.js"></script>
    <script>
      pdfjsLib.GlobalWorkerOptions.workerSrc = "./js/pdf.worker.min.js";

      // PDF文件的URL
      // const pdfUrl = 'http://localhost:8080/servlet/cert?cert_id=229&itm_id=193&tkh_id=0&isShowPrefix=false&lan=zh-cn';
      const pdfUrl = "./pdf/test.pdf";
    //   const pdfUrl = "./pdf/cert2.pdf";

      // 加载PDF文件并转换为图片
      pdfjsLib.getDocument(pdfUrl).promise.then(function (pdf) {
        const numPages = pdf.numPages;
        const pdfContainer = document.getElementById("pdf-container");

        // 遍历每一页并转换为图片
        for (let pageNumber = 1; pageNumber <= numPages; pageNumber++) {
          pdf.getPage(pageNumber).then(function (page) {
            const scale = 1;
            const viewport = page.getViewport({ scale: scale });

            const canvas = document.createElement("canvas");
            const context = canvas.getContext("2d");
            canvas.height = viewport.height;
            canvas.width = viewport.width;

            const renderContext = {
              canvasContext: context,
              viewport: viewport,
            };

            page.render(renderContext).promise.then(function () {
              const img = document.createElement("img");
              img.src = canvas.toDataURL("image/png");
              pdfContainer.appendChild(img);
            });
          });
        }
      });
    </script>
  </body>
</html>
